<?php

/**
 * Creating HTML to visualizise data about subdivisions
 * 
 * @author Aldis Rameika
 */
class LoadViewDesign {
    const TABLE_MODE_QUANTYTI = 0;
    const TABLE_MODE_TIME = 1;
    
    const DIAGRAM_MODE_ADMINISTRATED = 0;
    const DIAGRAM_MODE_RECEIVED = 1;
    const DIAGRAM_MODE_PREVIOUS = 2;
    const DIAGRAM_MODE_TIME = 3;
        
    
    /**
     * Table for subdivisions
     * 
     * @param array $dates          [date]=>boolean is predicted
     * @param array $subdivisions   [code]=>name
     * @param array $time_groups    [subdivision][date]=>TimeGroup
     * @param $mode                 see TABLE_MODE_*
     */
    public static function table_sub($dates, $subdivisions, $time_groups, $mode = self::TABLE_MODE_QUANTYTI) {
        global $row_index;
        ?><div class="data_table"><table class="data_table" border="0">
            <?php
                self::table_header($dates, 'Padalinys | Laikotarpis');
                foreach ($time_groups as $subdivsion_code=>$row) {
                    $subdivision_name = htmlspecialchars($subdivisions[$subdivsion_code]);
                    $row_class = $row_index ? ' class="r1"' : '';
                    $row_index = $row_index ? false : true;
                    echo "<tr $row_class><td class='head_column'>$subdivision_name</td>";
                    foreach ($row as $date=>$time_group) {
                        $received = $time_group->sum_received();
                        $previous = $time_group->sum_previous();
                        $administrated = $time_group->sum_administrated();
                        $time = $time_group->sum_time_used();
                        $predicted = $time_group->predicted ? 'predicted' : '';
                        if ($mode == self::TABLE_MODE_QUANTYTI) {
                            if ($predicted) {
                                $predicted = " class='$predicted'";
                            }
                            echo "<td $predicted>";
                                echo "<span class='received'>$received</span><br/>";
                                echo "<span class='previous'>$previous</span><br/>";
                                echo "<span class='addministrated'>$administrated</span><br/>";
                            echo '</td>';
                        } else {
                            echo "<td class='time $predicted'>$time</td>";
                        }
                    }
                    echo '</tr>';
                }
            ?>
        </table></div>
        <?php
    }
    
    /**
     * Comparison table for subdivisions
     * 
     * @param array $dates          [date]=>boolean is predicted
     * @param array $subdivisions   [code]=>name
     * @param array $time_groups1   [subdivision][date]=>TimeGroup
     * @param array $time_groups2   [subdivision][date]=>TimeGroup
     * @param $mode                 see TABLE_MODE_*
     */
    public static function table_compare_sub($dates, $subdivisions, $time_groups1, $time_groups2) {
        global $row_index;
        ?><div class="data_table"><table class="data_table" border="0">
            <?php
                self::table_header($dates, 'Padalinys | Laikotarpis');
                foreach ($time_groups1 as $subdivsion_code=>$row) {
                    $subdivision_name = htmlspecialchars($subdivisions[$subdivsion_code]);
                    $row_class = $row_index ? ' class="r1"' : '';
                    $row_index = $row_index ? false : true;
                    echo "<tr $row_class><td class='head_column'>$subdivision_name</td>";
                    foreach ($row as $date=>$time_group1) {
                        $received1 = $time_group1->sum_received();
                        $previous1 = $time_group1->sum_previous();
                        $administrated1 = $time_group1->sum_administrated();
                        $time1 = $time_group1->sum_time_used();
                        
                        $time_group2 = $time_groups2[$subdivsion_code][$date];
                        $received2 = $time_group2->sum_received();
                        $previous2 = $time_group2->sum_previous();
                        $administrated2 = $time_group2->sum_administrated();
                        $time2 = $time_group2->sum_time_used();

                        $received = self::percent_diff($received1, $received2);
                        $previous = self::percent_diff($previous1, $previous2);
                        $administrated = self::percent_diff($administrated1, $administrated2);
                        $time = self::percent_diff($time1, $time2);
                        
                        $predicted = $time_group1->predicted ? 'predicted' : '';
                        if ($predicted) {
                            $predicted = " class='$predicted'";
                        }
                        echo "<td $predicted>";
                            echo "<span class='received'>$received</span><br/>";
                            echo "<span class='previous'>$previous</span><br/>";
                            echo "<span class='addministrated'>$administrated</span><br/>";
                            echo "<span class='time'>$time</span><br/>";
                        echo '</td>';
                    }
                    echo '</tr>';
                }
            ?>
        </table></div>
        <?php
    }
    
    public static function table_compare_is($dates, $is_names, $is_time_groups1, $is_time_groups2) {
        global $row_index;
        ?><div class="data_table"><table class="data_table" border="0">
            <?php
                self::table_header($dates, 'Informacinė sistema | Laikotarpis');
                foreach ($is_time_groups1 as $is=>$row) {
                    $is_name = htmlspecialchars($is_names[$is]);
                    $row_class = $row_index ? ' class="r1"' : '';
                    $row_index = $row_index ? false : true;
                    echo "<tr $row_class><td class='head_column'>$is_name</td>";
                    foreach ($row as $date=>$is_time_group1) {
                        $administrated1 = $is_time_group1->sum_n;
                        $time1 = $is_time_group1->sum_time;
                        
                        $time_group2 = $is_time_groups2[$is][$date];
                        $administrated2 = $time_group2->sum_n;
                        $time2 = $time_group2->sum_time;

                        $administrated = self::percent_diff($administrated1, $administrated2);
                        $time = self::percent_diff($time1, $time2);
                        
                        $predicted = $is_time_group1->predicted ? 'predicted' : '';
                        if ($predicted) {
                            $predicted = " class='$predicted'";
                        }
                        echo "<td $predicted>";
                            echo "<span class='addministrated'>$administrated</span><br/>";
                            echo "<span class='time'>$time</span><br/>";
                        echo '</td>';
                    }
                    echo '</tr>';
                }
            ?>
        </table></div>
        <?php
    }    
    
    private static function percent_diff($value1, $value2) {
        if ($value1 == 0 && $value2 != 0) {
            return $value2;
        } else if ($value2 == 0 && $value1 != 0) {
            return $value1;
        } else if ($value1 < $value2) {
            $value = ($value2 / $value1) * 100;
        } else if ($value1 > $value2) {
            $value = -($value1 / $value2) * 100;
        } else {
            return '<span class="zero">0%</span>';
        }
        if (abs($value) < 100) {
            $color = dechex($value * 128);
        } else {
            $color = '88';
        }
        if ($value > 0) {
            $color = $color . '2222';
            $value = '+' . round($value, 1);
        } else {
            $color = '22' . $color . '22';
            $value = round($value, 1);
        }
        $border_size = round(abs($value) / 50);
        return "<span style='border-left: {$border_size}px solid #$color;'>$value%</span>";
    }
    
    public static function table_is($dates, $is_names, $is_time_groups, $mode = self::TABLE_MODE_QUANTYTI) {
        global $row_index;
        ?><div class="data_table"><table class="data_table" border="0">
            <?php
                self::table_header($dates, 'IS | Laikotarpis');
                
                foreach ($is_time_groups as $is_code=>$row) {
                    $is_name = htmlspecialchars($is_names[$is_code]);
                    $row_class = $row_index ? ' class="r1"' : '';
                    $row_index = $row_index ? false : true;
                    echo "<tr $row_class><td class='head_column'>$is_name</td>";
                    foreach ($row as $date=>$is_time_group) {
                        $used = $is_time_group->sum_n;
                        $time = $is_time_group->sum_time;
                        $predicted = $is_time_group->predicted ? ' class="predicted"' : '';
                        echo "<td $predicted>";
                            if ($mode == self::TABLE_MODE_TIME) {
                                echo "<span class='time'>$time</span>";
                            } else {
                                echo "<span class='received'>$used</span>";
                            }
                        echo '</td>';
                    }
                    echo '</tr>';
                }
            ?>
        </table></div>
        <?php
    }
    
    private static function table_header($dates, $informationCell) {
        $informationCell = htmlspecialchars($informationCell);
        ?><tr class="head_row"><?php
            echo "<td class='corner'>$informationCell</td>";
            foreach ($dates as $date=>$is_predicted) {
                $time = htmlspecialchars($date);
                $date = str_replace('-', ' - ', $date);
                $class = $is_predicted ? 'class="predicted"' : '';
                echo "<td $class>$date</td>";
            }
        ?></tr><?php
    }
    
    /**
     * Paints a dotted sub chart 
     * @param array $dates              [date]=>boolean is predicted
     * @param array $subdivisions       [code]=>name
     * @param array $sub_time_groups    [subdivision][date]=>TimeGroup
     * @param $mode                     see DIAGRAM_MODE_*
     */

    public static function dotted_sub($dates, $subdivisions, $sub_time_groups, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        $column_count = count($sub_time_groups);
        $row_count = self::get_row_count($sub_time_groups);
// TODO: automatinis grazinimass (ciklas4)
        ?>
        <script>
            $('#status').text('Atnaujinamos diagramos');
            $('#status').css('display', 'block');
            
            $(document).ready(function() {
                $('#status').text('Atnaujinamos diagramos');
                $('#status').css('display', 'block');
                
                var r = Raphael("dotted_sub_table"),
                row_width = <? echo self::generate_rows($column_count, $row_count); ?>,
                col_height = <? echo self::generate_columns($column_count, $row_count); ?>,
                data = <? echo self::generate_subs_data($subdivisions, $sub_time_groups, $mode); ?>,
                                                                                                                                                                                                                                                                                                                                                                                                
                is_axis = <? echo self::generate_names($subdivisions); ?>,
                date_axis = <? echo self::generate_dates($dates, "dotted"); ?>;

                r.dotchart(10, 10, 1600, 350, row_width, col_height, data, {symbol: "o", max: 10, heat: true, axis: "0 0 1 1", axisxstep: <? echo $row_count - 1; ?>, axisystep: <? echo $column_count - 1; ?>, axisxlabels: date_axis, axisxtype: " ", axisytype: " ", axisylabels: is_axis}).hover(function () {
                    this.marker = this.marker || r.tag(this.x, this.y, this.value, 0, this.r + 2).insertBefore(this);
                    this.marker.show();
                }, function () {
                    this.marker && this.marker.hide();
                });
                
                $('#status').css('display', 'none');
            });
        </script>
        <div id="dotted_sub_table"></div>
        <?php
    }

    /*
     * Paints a dotted IS chart 
     * @param array $dates              [date]=>boolean is predicted
     * @param array $is_names           [code]=>name
     * @param array $is_time_groups     [subdivision][date]=>TimeGroup
     * @param $mode                     see DIAGRAM_MODE_*
     */

    public static function dotted_is($dates, $is_names, $is_time_groups, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        $column_count = count($is_time_groups);
        $row_count = self::get_row_count($is_time_groups);
// TODO: automatinis grazinimas (ciklas4)
        ?>
        <script>
            $('#status').text('Atnaujinamos diagramos');
            $('#status').css('display', 'block');
            
            $(document).ready(function() {
                $('#status').text('Atnaujinamos diagramos');
                $('#status').css('display', 'block');
                
                var r = Raphael("dotted_is_table"),
                row_width = <? echo self::generate_rows($column_count, $row_count); ?>,
                col_height = <? echo self::generate_columns($column_count, $row_count); ?>,
                data = <? echo self::generate_is_data($is_names, $is_time_groups, $mode); ?>,
                                                                                                                                                                                                                                                                                                                                                                                                
                is_axis = <? echo self::generate_names($is_names); ?>,
                date_axis = <? echo self::generate_dates($dates, "dotted"); ?>;

                r.dotchart(10, 10, 1600, 310, row_width, col_height, data, {symbol: "o", max: 10, heat: true, axis: "0 0 1 1", axisxstep: <? echo $row_count - 1; ?>, axisystep: <? echo $column_count - 1; ?>, axisxlabels: date_axis, axisxtype: " ", axisytype: " ", axisylabels: is_axis}).hover(function () {
                    this.marker = this.marker || r.tag(this.x, this.y, this.value, 0, this.r + 2).insertBefore(this);
                    this.marker.show();
                }, function () {
                    this.marker && this.marker.hide();
                });
                
                $('#status').css('display', 'none');
            });
        </script>
        <div id="dotted_is_table"></div>
        <?php
    }

    /**
     * Paints a linear SUB chart 
     * @param array $dates              [date]=>boolean is predicted
     * @param array $subdivisions       [code]=>name
     * @param array $sub_time_groups    [subdivision][date]=>TimeGroup
     * @param $mode [0: show administrated, 1: show received, 2: show left over]
     * @param $mode                     see DIAGRAM_MODE_*
     */
    public static function linear_sub($dates, $subdivisions, $sub_time_groups, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        $column_count = count($sub_time_groups);
        $row_count = self::get_row_count($sub_time_groups);
        // TODO: automatinis grazinimass (ciklas4)
        ?>
        <script>
            $('#status').text('Atnaujinamos diagramos');
            $('#status').css('display', 'block');

            
            var chart;
            $(document).ready(function() {
                $('#status').text('Atnaujinamos diagramos');
                $('#status').css('display', 'block');
                
                chart = new Highcharts.Chart(
        <?
        echo "{\n";
        echo self::generate_chart("linear_sub_table") . ",\n";
        echo self::generate_colors() . ",\n";
        echo self::generate_title("") . ",\n";
        echo self::generate_subtitle("") . ",\n";
        echo self::generate_xAxis($dates) . ",\n";
        if ($mode == self::DIAGRAM_MODE_TIME) {
            echo self::generate_yAxis("Darbo laikas valandomis") . ",\n";
        } else {
            echo self::generate_yAxis("Paraiškų skaičius") . ",\n";
        }
        echo self::generate_tooltip() . ",\n";
        //echo self::generate_legend() . ",\n";
        echo self::generate_sub_series($subdivisions, $sub_time_groups, $mode) . "\n";
        echo " }";
        ?>);	
            $('#status').css('display', 'none');
            
            });
        </script>
        <div id="linear_sub_table"></div>
        <?php
    }

    /**
     * Paints a linear SUB chart 
     * @param array $dates              [date]=>boolean is predicted
     * @param array $subdivisions       [code]=>name
     * @param array $sub_time_groups    [subdivision][date]=>TimeGroup
     * @param $mode [0: show administrated, 1: show received, 2: show left over]
     * @param $mode                     see DIAGRAM_MODE_*
     */
    public static function linear_sub2($dates, $subdivisions, $sub_time_groups, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        global $buffDiagramIndex;
        $column_count = count($sub_time_groups);
        $row_count = self::get_row_count($sub_time_groups);
        // TODO: automatinis grazinimass (ciklas4)
        $name = 'diagram' . (++$buffDiagramIndex);
        $size = '1600x400';
        $predicetd = array_search(true, $dates);
        $date_text = array_keys($dates);
        $predicetd = array_search($predicetd, $date_text);
        ?>
        <div class="buff_diagram" id="div_<?=$name;?>"><pre><canvas id="<?=$name;?>"></canvas></pre></div>
        <script type="text/javascript">
            $('#status').text('Atnaujinamos diagramos');
            $('#status').css('display', 'block');
            
            var chart;
            $(document).ready(function() {
                $('#status').text('Atnaujinamos diagramos');
                $('#status').css('display', 'block');
            
                /* Data */
                var chartData = {
                <?
                echo self::generate_xAxis($dates) . ",\n";
                if ($mode == self::DIAGRAM_MODE_TIME) {
                    echo self::generate_yAxis("Darbo laikas valandomis") . ",\n";
                } else {
                    echo self::generate_yAxis("Paraiškų skaičius") . ",\n";
                }
                echo self::generate_sub_series($subdivisions, $sub_time_groups, $mode) . "\n";
                echo " ";
                ?>};
                
                /* Drawing */
                var g = new Bluff.Line('<?=$name;?>', '<?=$size;?>');
                g.theme_greyscale();

                g.hide_dots = true;
                g.title_font_size = '5px';
                g.legend_font_size = '8px';
                g.marker_font_size = '3px';

                g.hide_legend = true;
                g.hide_title = true;
                
                g.top_margin = 2;
                g.left_margin = 2;
                g.right_margin = 2;
                g.bottom_margin = 15;
                g.tooltips = true;

                g.labels = [];
                for(var i in chartData.xAxis.categories) {
                    var date = chartData.xAxis.categories[i].replace(' ', '\n');
                    date = date.substring(0, 2) + "\n" + date.substring(2);
                    g.labels.push(date);
                    
                }

                for(var i in chartData.series) {
                    var line = chartData.series[i];
                    g.data(line.name, line.data);
                }

                g.draw();
                
                var month = 0;
                $.each( $('#div_<?=$name;?> div.bluff-text'), function(i, div) {
                    if (div.innerHTML.indexOf('\n') != -1) {
                        var date = div.innerHTML.substring(0, 2) + div.innerHTML.substring(3, 5) + ' ' + div.innerHTML.substring(6);
                        div.title = date;
                        if (month >= <?=$predicetd;?>) {
                            $(div).addClass('predicted');
                            div.title = div.title + ' (Prognozuojama)'
                        }
                        month++;
                    }
                });
                
                $('#status').css('display', 'none');
            });
        </script>
        <?php
    }
    
    public static function linear_compare($dates, $subdivisions, $time_groups1, $time_groups2, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        global $buffDiagramIndex;
        $ids = array();
        ?><div class="buff_diagram"><?
        foreach ($subdivisions as $code=>$value) {
            $buffDiagramIndex++;
            $ids[$code] = "g_$buffDiagramIndex";
            echo "<canvas id='{$ids[$code]}'></canvas>";
        }
        ?></div><?
        $size = '500x50';
        ?>
        <script type="text/javascript">
                $(document).ready(function() {
                    <?
                        foreach ($subdivisions as $subdivision=>$name) {
                            $id = $ids[$subdivision];
                            $title1 = $subdivisions[$subdivision] . '(Sena)';
                            $title2 = $subdivisions[$subdivision] . '(Nauja)';
                            self::bluff_draw_row($id, $size, $title1, $title2, $time_groups1[$subdivision], $time_groups2[$subdivision], $mode);
                        }
                    ?>
                });
        </script>
        <?
    }
    
    
    private static function bluff_draw_row($id, $size, $title1, $title2, $line1, $line2, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        $series1 = array();
        $series2 = array();
        foreach ($line1 as $date=>$time_group) {
            if ($mode == self::DIAGRAM_MODE_ADMINISTRATED) {
                $series1[] = $time_group->sum_administrated();
                $series2[] = $line2[$date]->sum_administrated();
            } else {
                //TODO: received, previous etc
                $series1[] = $time_group->sum_time_used();
                $series2[] = $line2[$date]->sum_time_used();
            }
        }
        $series1 = implode(',', $series1);
        $series2 = implode(',', $series2);
        echo "var $id = new Bluff.Mini.Bar('$id', '$size');\n";
        echo "$id.hide_legend = true;\n";
        echo "$id.hide_title = true;\n";
        echo "$id.hide_line_markers = true;\n";
        echo "$id.hide_mini_legend = true;\n";
        echo "$id.tooltips = true;\n";
        echo "$id.tooltips = true;\n";
        echo "$id.top_margin = 0;\n";
        echo "$id.left_margin = 0;\n";
        echo "$id.right_margin = 0;\n";
        echo "$id.bottom_margin = 0;\n";

        echo "$id.data(\"$title1\", [$series1]);\n";
        echo "$id.data(\"$title2\", [$series2]);\n";
        
        echo "$id.draw();";
    }
   
    /*
     * Paints a linear IS chart 
     * @param array $dates              [date]=>boolean is predicted
     * @param array $is_names           [code]=>name
     * @param array $is_time_groups     [subdivision][date]=>TimeGroup
     * @param $mode                     see DIAGRAM_MODE_*
     */

    public static function linear_is($dates, $is_names, $is_time_groups, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        $column_count = count($is_time_groups);
        $row_count = self::get_row_count($is_time_groups);
        // TODO: automatinis grazinimas (ciklas4)
        ?>
        <script>
            var chart;
            $(document).ready(function() {
                chart = new Highcharts.Chart(
        <?
        echo "{\n";
        echo self::generate_chart("linear_is_table") . ",\n";
        echo self::generate_colors() . ",\n";
        echo self::generate_title("") . ",\n";
        echo self::generate_subtitle("") . ",\n";
        echo self::generate_xAxis($dates) . ",\n";
        if ($mode == self::DIAGRAM_MODE_TIME) {
            echo self::generate_yAxis("Darbo laikas valandomis") . ",\n";
        } else {
            echo self::generate_yAxis("Paraiškų skaičius") . ",\n";
        }
        echo self::generate_tooltip() . ",\n";
        //echo self::generate_legend() . ",\n";
        echo self::generate_is_series($is_names, $is_time_groups, $mode) . "\n";
        echo " }";
        ?>);		
            });
        </script>
        <div id="linear_is_table"></div>
        <?php
    }

    // Functions for DOTTED chart

    /*
     * Generating names for table
     */

    private static function generate_names($names_array) {
        $generated_names = "[";
        $temp_names = array();

        foreach ($names_array as $code => $title) {
            $temp_names[count($temp_names)] = $code;
        }

        // Reversing order for javascript
        $names_count = count($temp_names);
        for ($i = $names_count - 1; $i >= 0; $i--) {
            $generated_names .= '"' . $temp_names[$i] . '",';
        }

        $generated_names = substr_replace($generated_names, "]", -1);
        return $generated_names;
    }

    /*
     * Generating dates for table
     */

    private static function generate_dates($dates, $type, &$prediction_starts = null) {
        $prediction_starts = -0.5;
        $generated_dates = "[";
        if ($type == "dotted") {
            foreach ($dates as $date => $is_forecast) {
                $generated_dates .= '"' . substr($date, 0, 4) . "\\n" . substr($date, 5, 2) . '",';
            }
        } else {
            $month_count = 0.0;
            foreach ($dates as $date => $is_forecast) {
                if ($prediction_starts == -0.5 && $is_forecast == 1) {
                    $prediction_starts = $month_count;
                }
                $generated_dates .= '"' . substr($date, 0, 4) . " " . substr($date, 5, 2) . '",';
                $month_count += 1.0;
            }
        }

        $generated_dates = substr_replace($generated_dates, "]", -1);
        return $generated_dates;
    }

    /**
     * Generating data for SUBS table
     * 
     * @param $mode     see DIAGRAM_MODE_*
     */
    private static function generate_subs_data($subs_names, $subs_time_groups, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        $generated_data = "[";

        switch ($mode) {
            // Show administrated
            case self::DIAGRAM_MODE_ADMINISTRATED:
                foreach ($subs_names as $sub_code => $sub_title) {
                    foreach ($subs_time_groups[$sub_code] as $time_group) {
                        $generated_data .= $time_group->sum_administrated() . ",";
                    }
                }
                break;
            // Show received
            case self::DIAGRAM_MODE_RECEIVED:
                foreach ($subs_names as $sub_code => $sub_title) {
                    foreach ($subs_time_groups[$sub_code] as $time_group) {
                        $generated_data .= $time_group->sum_received() . ",";
                    }
                }
                break;
            // Show left over
            case self::DIAGRAM_MODE_PREVIOUS:
                foreach ($subs_names as $sub_code => $sub_title) {
                    foreach ($subs_time_groups[$sub_code] as $time_group) {
                        $generated_data .= $time_group->sum_previous() . ",";
                    }
                }
                break;
           // Time
           case self::DIAGRAM_MODE_TIME:
               foreach ($subs_names as $sub_code => $sub_title) {
                    foreach ($subs_time_groups[$sub_code] as $time_group) {
                        $generated_data .= $time_group->sum_time_used() . ",";
                    }
                }
        }

        $generated_data = substr_replace($generated_data, "]", -1);
        return $generated_data;
    }

    /*
     * Generating data for IS table
     */

    private static function generate_is_data($is_names, $is_time_groups, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        $generated_data = "[";

        // Two different cycles for performance
        if ($mode == self::DIAGRAM_MODE_TIME) {
            foreach ($is_names as $is_code => $is_title) {
                foreach ($is_time_groups[$is_code] as $time_group) {
                    $generated_data .= $time_group->sum_time . ",";
                }
            }
        } else {
            foreach ($is_names as $is_code => $is_title) {
                foreach ($is_time_groups[$is_code] as $time_group) {
                    $generated_data .= $time_group->sum_n . ",";
                }
            }
        }


        $generated_data = substr_replace($generated_data, "]", -1);
        return $generated_data;
    }

    /*
     * Generating columns for table
     * @param <$height> describes how many horizontal rows we will have
     * @param <$width> describes how many columns in a row we will have
     */

    private static function generate_columns($height, $width) {
        $generated_columns = "[";
        for ($col = $height; $col >= 1; $col--) {
            for ($row = 1; $row <= $width; $row++) {
                $generated_columns .= $col . ",";
            }
        }

        $generated_columns = substr_replace($generated_columns, "]", -1);
        return $generated_columns;
    }

    /*
     * Generating row for table
     * @param <$height> describes how many horizontal rows we will have
     * @param <$width> describes how many columns in a row we will have
     */

    private static function generate_rows($height, $width) {
        $generated_rows = "[";
        for ($row = 0; $row < $height; $row++) {
            for ($col = 0; $col < $width; $col++) {
                $generated_rows .= $col . ",";
            }
        }

        $generated_rows = substr_replace($generated_rows, "]", -1);
        return $generated_rows;
    }

    /*
     * Returns how many different dates are in <$is_time_groups>
     * @return row_count
     */

    private static function get_row_count($time_groups) {
        $row_count = 0;
        foreach ($time_groups as $is_code_data) {
            $row_count = count($is_code_data);
            break;
        }
        return $row_count;
    }

    // Functions for LINEAR chart

    /*
     * Generating linear chart
     * @return chart: {...}
     */

    private static function generate_chart($table_div) {
        $generated_chart = "chart: {
            renderTo: '" . $table_div . "',
            defaultSeriesType: 'spline',
            marginRight: 20,
            width: 1900,
            height: 330
            }";
        return $generated_chart;
    }
    
    /*
     * Generating default colors for lines
     * @return colors: {...}
     */
    
    private static function generate_colors() {
        $generated_colors = "colors: [
	'#4572A7', 
	'#AA4643', 
	'#89A54E', 
	'#80699B', 
	'#3D96AE', 
	'#DB843D', 
	'#92A8CD', 
	'#A47D7C', 
	'#B5CA92',
        '#5F5F5F',
        '#C0EA00',
        '#EA71E0',
        '#EB7070'
        ]";
        
        return $generated_colors;
    }

    /*
     * Generating title for linear chart
     * @return title: {...}
     */

    private static function generate_title($chart_title) {
        $generated_title = "title: {
            text: '" . $chart_title . "'
            }";
        return $generated_title;
    }

    /*
     * Generating subtitle for linear chart
     * @return subtitle: {...}
     */

    private static function generate_subtitle($chart_subtitle) {
        $generated_subtitle = "subtitle: {
            text: '" . $chart_subtitle . "'
            }";
        return $generated_subtitle;
    }

    /*
     * Generating xAxis for linear chart
     * @return xAxis: {...} 
     */

    private static function generate_xAxis($dates) {
        $prediction_starts = -0.5;
        $generated_xAxis = "xAxis: { 
            tickLength: 30,
            categories: ";
        $generated_xAxis .= self::generate_dates($dates, "linear", $prediction_starts) . ",
            plotBands: [{
                from: " . ($prediction_starts - 0.5) . ",
                to: " . ($prediction_starts + 12.0) . ",
                color: 'rgba(68, 170, 213, .2)'
            }]
            }";
        return $generated_xAxis;
    }

    /*
     * Generates yAxis for linear chart
     * @return yAxis: {...}
     */

    private static function generate_yAxis($axis_title) {
        $generated_yAxis = "yAxis: { 
            title : {
                text: '" . $axis_title . "'
                },
            min: 0,
            showFirstLabel: false,
            plotLines: [{
            value: 0,
            width: 1,
            color: '#808080' }]
            }";
        return $generated_yAxis;
    }

    /*
     * Generating tooltip for linear on chart points
     * @return tooltip: {...}
     */

    private static function generate_tooltip() {
        $generated_tooltip = "tooltip: {
            formatter: function() {
                return '<b>'+ this.series.name +'</b><br/>'+
                    this.x.toString().substring(0, 4) + '-' + this.x.toString().substring(5, 7) + ': '+ this.y;
                }
            }";
        // TODO: could be bugs with date
        return $generated_tooltip;
    }

    /*
     * Generating legend for linear chart
     * @return legend: {...} 
     */

    private static function generate_legend() {
        $generated_legend = "legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            x: -10,
            y: 100,
            borderWidth: 0
            }";
        return $generated_legend;
    }

    /**
     * Generating data for linear chart
     * 
     * @param $mode see DIAGRAM_MODE_*
     * @return series: {...}
     */
    private static function generate_sub_series($sub_names, $sub_time_groups, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        $generated_series = "series: [
                ";

        switch ($mode) {
            // Show administrated
            case self::DIAGRAM_MODE_ADMINISTRATED;
                foreach ($sub_names as $code => $title) {
                    $generated_series .= " { name: '" . $code . "',
                        data: [";
                    foreach ($sub_time_groups[$code] as $time_group) {
                        $generated_series .= $time_group->sum_administrated() . ",";
                    }
                    $generated_series = substr_replace($generated_series, "] },", -1);
                }
                break;
            // Show received
            case self::DIAGRAM_MODE_RECEIVED:
                foreach ($sub_names as $code => $title) {
                    $generated_series .= " { name: '" . $code . "',
                        data: [";
                    foreach ($sub_time_groups[$code] as $time_group) {
                        $generated_series .= $time_group->sum_received() . ",";
                    }
                    $generated_series = substr_replace($generated_series, "] },", -1);
                }
                break;
            // Show left over
            case self::DIAGRAM_MODE_PREVIOUS:
                foreach ($sub_names as $code => $title) {
                    $generated_series .= " { name: '" . $code . "',
                        data: [";
                    foreach ($sub_time_groups[$code] as $time_group) {
                        $generated_series .= $time_group->sum_previous() . ",";
                    }
                    $generated_series = substr_replace($generated_series, "] },", -1);
                }
                break;
            // Time
            case self::DIAGRAM_MODE_TIME:
                foreach ($sub_names as $code => $title) {
                    $generated_series .= " { name: '" . $code . "',
                        data: [";
                    foreach ($sub_time_groups[$code] as $time_group) {
                        $generated_series .= $time_group->sum_time_used() . ",";
                    }
                    $generated_series = substr_replace($generated_series, "] },", -1);
                }
                break;
        }

        $generated_series = substr_replace($generated_series, "]", -1);
        return $generated_series;
    }

    private static function generate_is_series($is_names, $is_time_groups, $mode = self::DIAGRAM_MODE_ADMINISTRATED) {
        $generated_series = "series: [
                ";

        // Different cycles for performance
        if ($mode == self::DIAGRAM_MODE_TIME) {
            foreach ($is_names as $code => $title) {
                $generated_series .= " { name: '" . $code . "',
                    data: [";
                foreach ($is_time_groups[$code] as $time_group) {
                    $generated_series .= $time_group->sum_time . ",";
                }
                $generated_series = substr_replace($generated_series, "] },", -1);
            }
        } else {
            foreach ($is_names as $code => $title) {
                $generated_series .= " { name: '" . $code . "',
                    data: [";
                foreach ($is_time_groups[$code] as $time_group) {
                    $generated_series .= $time_group->sum_n . ",";
                }
                $generated_series = substr_replace($generated_series, "] },", -1);
            }
        }

        $generated_series = substr_replace($generated_series, "]", -1);
        return $generated_series;
    }

}